<template>
  <div class="pet-form-container">
    <el-card class="form-card">
      <div slot="header">
        <span>{{ isEdit ? '编辑宠物' : '添加宠物' }}</span>
      </div>
      <el-form ref="petForm" :model="petForm" :rules="rules" label-width="100px">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="petForm.name" placeholder="请输入宠物名称"></el-input>
        </el-form-item>
        
        <el-form-item label="宠物类别" prop="category">
          <el-select v-model="petForm.category" placeholder="请选择宠物类别">
            <el-option label="猫" value="猫"></el-option>
            <el-option label="狗" value="狗"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="品种" prop="breed">
          <el-input v-model="petForm.breed" placeholder="请输入宠物品种"></el-input>
        </el-form-item>
        
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="petForm.age" :min="0" :max="30"></el-input-number>
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="petForm.gender">
            <el-radio label="公">公</el-radio>
            <el-radio label="母">母</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="健康状况" prop="healthStatus">
          <el-input v-model="petForm.healthStatus" placeholder="请输入健康状况"></el-input>
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="petForm.description" rows="4" placeholder="请输入宠物描述"></el-input>
        </el-form-item>
        
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="pet-image-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :headers="headers">
            <img v-if="petForm.imageUrl" :src="petForm.imageUrl" class="pet-image">
            <i v-else class="el-icon-plus pet-image-uploader-icon"></i>
          </el-upload>
          <div class="image-tip">建议尺寸：400x400像素，支持jpg、png格式</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">{{ isEdit ? '保存修改' : '立即创建' }}</el-button>
          <el-button @click="$router.push('/pets')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createPet, updatePet, getPetDetail, uploadPetImage } from '@/api/pet'

export default {
  name: 'PetForm',
  data() {
    return {
      isEdit: false,
      petForm: {
        name: '',
        category: '',
        breed: '',
        age: 0,
        gender: '公',
        healthStatus: '',
        description: '',
        imageUrl: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择宠物类别', trigger: 'change' }
        ],
        breed: [
          { required: true, message: '请输入宠物品种', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入宠物年龄', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择宠物性别', trigger: 'change' }
        ]
      },
      loading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/pets/image'
    }
  },
  computed: {
    headers() {
      return {
        Authorization: `Bearer ${this.$store.state.user.token}`
      }
    }
  },
  methods: {
    // 获取宠物详情
    fetchPetDetail(id) {
      getPetDetail(id).then(response => {
        const { data } = response
        this.petForm = data
      })
    },
    // 提交表单
    handleSubmit() {
      this.$refs.petForm.validate(valid => {
        if (valid) {
          this.loading = true
          const request = this.isEdit
            ? updatePet(this.$route.params.id, this.petForm)
            : createPet(this.petForm)
          
          request
            .then(() => {
              this.$message.success(this.isEdit ? '修改成功' : '创建成功')
              this.$router.push('/pets')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    // 图片上传成功
    handleImageSuccess(response) {
      this.petForm.imageUrl = response.data
      this.$message.success('图片上传成功')
    },
    // 图片上传前的验证
    beforeImageUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPGOrPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPGOrPNG && isLt2M
    }
  },
  created() {
    // 判断是否是编辑模式
    this.isEdit = this.$route.name === 'PetEdit'
    if (this.isEdit) {
      this.fetchPetDetail(this.$route.params.id)
    }
  }
}
</script>

<style lang="scss" scoped>
.pet-form-container {
  padding: 20px;

  .form-card {
    max-width: 800px;
    margin: 0 auto;
  }

  .pet-image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;

    &:hover {
      border-color: #409EFF;
    }

    .pet-image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .pet-image {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }
  }

  .image-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }

  .el-button {
    margin-right: 20px;
  }
}
</style> 